import { ArticleApi } from '@/services/cms/CmsController';
import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { useAccess, useNavigate, useRequest, useSearchParams } from '@umijs/max';
import { Button, Flex, message, Modal, Popover, Space, Typography } from 'antd';
import { Key, useRef, useState } from 'react';
import './index.css'
import Settings from './components/settings';


const HomePage: React.FC = () => {
    const access = useAccess()
    let navigate = useNavigate();
    let [search, setSearch] = useSearchParams()
    let [showSetting, setShowSetting] = useState<number | null>(null)
    let refs = useRef<ActionType>();

    let { run: publish } = useRequest(ArticleApi.publish, { manual: true, throwOnError: true, onError() { message.error("发布失败") }, onSuccess() { refs.current?.reload() }, })
    let { run: unpublish } = useRequest(ArticleApi.unpublish, { manual: true, throwOnError: true, onError() { message.error("操作失败") }, onSuccess() { refs.current?.reload() }, })
    const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
    const rowSelection = {
        selectedRowKeys,
        onChange: (keys: Key[]) => setSelectedRowKeys(keys),
    };


    const columns: ProColumns<Cms.ArtileList>[] = [{
        title: '标题',
        dataIndex: "title",
        search: false,
        render: (dom, entity, index, action, schema) => {
            return <Flex vertical>
                <Typography.Link onClick={() => navigate(`editor?id=${entity.id}`)}>{entity.title}</Typography.Link>
                <Typography.Text style={{ maxWidth: "20rem" }} type='secondary' ellipsis={{}}>{entity.description}</Typography.Text>
            </Flex>
        },
    }, {
        title: '状态',
        dataIndex: "status",
        valueEnum: {
            0: { text: '待发布', color: 'grey' },
            1: { text: '审核中', color: 'orange' },
            2: { text: '已发布', status: 'Success' },
            3: { text: '被驳回', status: 'Error' },
        },
        width: "5rem",
        valueType: "select"
    }, {
        title: '发布时间',
        width: "10rem",
        dataIndex: "publish_at",
        valueType: "dateTime",
        sorter: true,
        search: false
    }, {
        title: '',
        width: "2rem",
        valueType: 'option',
        render: (_, record) => (
            <Popover content={<>
                <Flex vertical={true}>
                    <Button type="text" onClick={() => { setShowSetting(record.id) }}>设置</Button>

                    <Button type="text" onClick={() => { (record.status == 0 ? publish : unpublish)(record.id) }}>{record.status == 0 ? "发布" : "取消发布"}</Button>
                    <Button type="text" danger onClick={() => {
                        Modal.confirm({
                            title: "删除文章",
                            type: "error",
                            onOk: async () => { return ArticleApi.recycle(record.id) },
                            afterClose() { refs.current?.reload(); }
                        })
                    }}>删除</Button>
                </Flex>
            </>} trigger="click">
                <Button icon={<EllipsisOutlined />} size="small" type="link" ></Button>
            </Popover>
        ),
    }]
    return (
        <PageContainer ghost breadcrumbRender={false}
            header={{
                extra: <Space>
                    <Button onClick={() => navigate("recycle")}>回收站</Button>
                    <Button onClick={() => navigate("editor")} icon={<PlusOutlined />} color='primary' type='primary'>新建</Button>
                </Space>
            }}
        >
            <Settings id={showSetting} onClose={() => setShowSetting(null)} onFinish={() => refs.current?.reload()}></Settings>
            <ProTable columns={columns} params={{}} request={(p, o) => ArticleApi.list({ ...p, order: Object.entries(o).map(([k, v]) => `${k}-${v?.startsWith("a") ? "asc" : "desc"}`).join(",") })} actionRef={refs}
                rowKey={"id"}
                search={{
                    filterType: 'light',
                }}
                pagination={{
                    defaultCurrent: parseInt(search.get("page") || "") || 1,
                    defaultPageSize: 15,
                    showSizeChanger: true,
                    pageSizeOptions: [10, 15, 20, 25, 30, 50],
                    onChange(page, pageSize) { setSearch({ page: "" + page }) },
                }}
                options={{ density: false, setting: false }}
                rowSelection={{
                    selectedRowKeys,
                    hideSelectAll: false,
                    onChange: (keys: Key[]) => setSelectedRowKeys(keys),
                }}
            ></ProTable>
        </PageContainer>
    );
};

export default HomePage;
